package com.neteast.androidclient.newscenter.activity;

import com.kaixin.connect.Kaixin;
import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.provider.LoginInfoProvider;
import com.neteast.androidclient.newscenter.service.NetService;
import com.neteast.androidclient.newscenter.service.WidgetService;
import com.neteast.androidclient.newscenter.util.DeBugUtil;
import com.neteast.androidclient.newscenter.util.InfoUtil;
import com.neteast.androidclient.newscenter.util.JsonUtil;
import com.neteast.androidclient.newscenter.util.KaixinHelper;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import com.neteast.androidclient.newscenter.util.SinaWeiBoHelper;
import com.neteast.androidclient.newscenter.util.ValidateUtil;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.exception.RenrenException;
import com.renren.api.connect.android.feed.FeedPublishRequestParam;
import com.renren.api.connect.android.feed.FeedPublishResponseBean;
import com.renren.api.connect.android.view.RenrenAuthListener;
import com.tencent.weibo.api.User_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;
import com.weibo.net.Weibo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class UserCenterActivity extends Activity{
	/**获取用户中心信息失败*/
	private static final int REQUEST_USER_CENTER_ERROR = 0;
	/**获取用户中心信息成功*/
	private static final int REQUEST_USER_CENTER_SUCCESS = 1;
	/**编辑用户中心信息失败*/
	protected static final int EDIT_USER_CENTER_ERROR = 2;
	/**编辑用户中心信息成功*/
	protected static final int EDIT_USER_CENTER_SUCCESS = 3;
	/**绑定QQ成功*/
	protected static final int BANDING_QQ_SUCCESS = 4;
	/**绑定QQ失败*/
	protected static final int BANDING_QQ_ERROR = 5;
	
	private Activity context;
	
	private View displayState;
	private View editState;
	
	private TextView tvUsername;
	private TextView tvIdentityCard;
	private TextView tvLove;
	private TextView tvQQ;
	private TextView tvMSN;
	private TextView tvSchool;
	private TextView tvOrganization;
	
	private EditText etUsername;
	private EditText etIdentityCard;
	private EditText etLove;
	private EditText etQQ;
	private EditText etMSN;
	private EditText etSchool;
	private EditText etOrganization;
	
	private Bundle userCenterInfo;
	
	private ProgressDialog getDialog;
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REQUEST_USER_CENTER_SUCCESS:
				getDialog.dismiss();
				Toast.makeText(context, "获取用户信息成功", Toast.LENGTH_SHORT).show();
				btnEditInfo.setEnabled(true);
				setDisplayContent();
				break;
			case REQUEST_USER_CENTER_ERROR:
				getDialog.dismiss();
				Toast.makeText(context, "获取用户信息失败", Toast.LENGTH_SHORT).show();
				btnEditInfo.setEnabled(false);
				break;
			case EDIT_USER_CENTER_ERROR:
				editDialog.dismiss();
				Toast.makeText(context, "编辑用户信息失败", Toast.LENGTH_SHORT).show();
				userCenterInfo=new Bundle(cloneBundle);
				setDisplayContent();
				editState.setVisibility(View.GONE);
				displayState.setVisibility(View.VISIBLE);
				break;
			case EDIT_USER_CENTER_SUCCESS:
				editDialog.dismiss();
				Toast.makeText(context, "编辑用户信息成功", Toast.LENGTH_SHORT).show();
				setDisplayContent();
				editState.setVisibility(View.GONE);
				displayState.setVisibility(View.VISIBLE);
				break;
			case SinaWeiBoHelper.LOGOUT_SUCCESS:
				Log.i("test", "LOGOUT_SUCCESS");
				btnSina.setText("已绑定");
				btnSina.setEnabled(false);
				break;
			case SinaWeiBoHelper.LOGOUT_ERROR:
				Log.i("test", "LOGOUT_ERROR");
				break;
			case BANDING_QQ_SUCCESS:
				btnQQ.setText("已绑定");
				btnQQ.setEnabled(false);
				Toast.makeText(context, "绑定QQ成功", Toast.LENGTH_SHORT).show();
				break;
			case BANDING_QQ_ERROR:
				Log.i("test", "BANDING_QQ_ERROR");
				Toast.makeText(context, "绑定QQ失败", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	private Button btnEditInfo;
	private Bundle cloneBundle;
	private ProgressDialog editDialog;
	private Thread requestInfoThread;
	private View layout_userCenter;
	private View layout_shareCenter;
	private LayoutParams layoutParams;
	
	private Button btnSina;
	private Button btnQQ;
	private Button btnRenRen;
	private Button btnKaixin;
	private Renren renren;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		layoutParams = new LayoutParams(350, ViewGroup.LayoutParams.MATCH_PARENT);
		layout_userCenter = LayoutInflater.from(context).inflate(R.layout.layout_info_center, null);
		layout_shareCenter = LayoutInflater.from(context).inflate(R.layout.layout_share_main, null);
		setContentView(layout_userCenter,layoutParams);
		createDialog();
		getDialog.show();
		
		requestInfoThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					userCenterInfo = InfoUtil.getUserCenterInfo(context);
					handler.sendEmptyMessage(REQUEST_USER_CENTER_SUCCESS);
				} catch (Exception e) {
					Log.e("test", e.getMessage(),e);
					DeBugUtil.printException(context, e);
					handler.sendEmptyMessage(REQUEST_USER_CENTER_ERROR);
				}
			}
		});
		requestInfoThread.start();
		init();
	}
	private void createDialog() {
		getDialog = new ProgressDialog(context);
		getDialog.setTitle("提示");
		getDialog.setMessage("获取用户信息，请稍后");
		getDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
		editDialog = new ProgressDialog(context);
		editDialog.setTitle("提示");
		editDialog.setMessage("保存用户信息，请稍后");
		editDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	}

	private void init() {
		findView();
		initView();
	}
	public static final String RENREN_APP_ID="189176";
	public static final String RENREN_API_KEY="7e3473bf828b4e159de5b6b7b9270d71";
	public static final String RENREN_Secret_Key="4d0472839f3e4fce9c3eca2c39284c97";
	public static final String RENREN_REDIRECT_URL="http://www.163.com";
	private void initView() {
		if (Weibo.getInstance().isSessionValid()) {
			btnSina.setText("已绑定");
			btnSina.setEnabled(false);
		} else {
			btnSina.setEnabled(true);
			btnSina.setText("绑定");
		}
		if (Kaixin.getInstance().isSessionValid()) {
			btnKaixin.setText("已绑定");
			btnKaixin.setEnabled(false);
		} else {
			btnKaixin.setText("绑定");
			btnKaixin.setEnabled(true);
		}
		if (QQWebViewActivity.isValidate(context)) {
			btnQQ.setText("已绑定");
			btnQQ.setEnabled(false);
		}else {
			btnQQ.setText("绑定");
			btnQQ.setEnabled(true);
		}
		renren = new Renren(RENREN_API_KEY, RENREN_Secret_Key, RENREN_APP_ID, context);
		if (renren.isAccessTokenValid()) {
			btnRenRen.setText("已绑定");
			btnRenRen.setEnabled(false);
		}else {
			btnRenRen.setText("绑定");
			btnRenRen.setEnabled(true);
		}
	}
	/**
	 * 根据获取到的信息，设置显示状态的内容
	 */
	private void setDisplayContent() {
		if (userCenterInfo!=null) {
			tvUsername.setText(userCenterInfo.getString("username"));
			tvIdentityCard.setText(userCenterInfo.getString("identityCard"));
			tvLove.setText(userCenterInfo.getString("love"));
			tvQQ.setText(userCenterInfo.getString("QQ"));
			tvMSN.setText(userCenterInfo.getString("MSN"));
			tvSchool.setText(userCenterInfo.getString("school"));
			tvOrganization.setText(userCenterInfo.getString("organization"));
		}
	}
	
	/**
	 * 根据获取到的信息，设置编辑状态的内容
	 */
	private void setEditContent() {
		if (userCenterInfo!=null) {
			etUsername.setText(userCenterInfo.getString("username"));
			etIdentityCard.setText(userCenterInfo.getString("identityCard"));
			etLove.setText(userCenterInfo.getString("love"));
			etQQ.setText(userCenterInfo.getString("QQ"));
			etMSN.setText(userCenterInfo.getString("MSN"));
			etSchool.setText(userCenterInfo.getString("school"));
			etOrganization.setText(userCenterInfo.getString("organization"));
		}
	}
	/**
	 * 将编辑后的内容更新到Bundle中
	 */
	private void saveEditInfoToBundle() {
		userCenterInfo.putString("love", etLove.getText().toString());
		String QQ = etQQ.getText().toString();
		if (ValidateUtil.validateIm("QQ", QQ)) {
			userCenterInfo.putString("QQ", QQ);
		}else {
			Toast.makeText(context, "QQ格式错误", Toast.LENGTH_SHORT).show();
			etQQ.requestFocus();
		}
		
		String MSN = etMSN.getText().toString();
		if (ValidateUtil.validateEmail(MSN)) {
			userCenterInfo.putString("MSN", MSN);
		}else {
			Toast.makeText(context, "MSN格式错误", Toast.LENGTH_SHORT).show();
			etMSN.requestFocus();
		}
		userCenterInfo.putString("school", etSchool.getText().toString());
		userCenterInfo.putString("organization", etOrganization.getText().toString());
	}
	
	
	private void findView() {
		displayState = layout_userCenter.findViewById(R.id.displayState);
		editState = layout_userCenter.findViewById(R.id.editState);
		
		btnEditInfo = (Button) layout_userCenter.findViewById(R.id.editInfo);
		tvUsername = (TextView) layout_userCenter.findViewById(R.id.username);
		tvIdentityCard = (TextView) layout_userCenter.findViewById(R.id.identityCard);
		tvLove = (TextView) layout_userCenter.findViewById(R.id.love);
		tvQQ = (TextView) layout_userCenter.findViewById(R.id.QQ);
		tvMSN = (TextView) layout_userCenter.findViewById(R.id.MSN);
		tvSchool = (TextView) layout_userCenter.findViewById(R.id.school);
		tvOrganization = (TextView) layout_userCenter.findViewById(R.id.organization);
		
		etUsername = (EditText) layout_userCenter.findViewById(R.id.edit_username);
		etIdentityCard = (EditText) layout_userCenter.findViewById(R.id.edit_identityCard);
		etLove = (EditText) layout_userCenter.findViewById(R.id.edit_love);
		etQQ = (EditText) layout_userCenter.findViewById(R.id.edit_QQ);
		etMSN = (EditText) layout_userCenter.findViewById(R.id.edit_MSN);
		etSchool = (EditText) layout_userCenter.findViewById(R.id.edit_school);
		etOrganization = (EditText) layout_userCenter.findViewById(R.id.edit_organization);
		
		btnSina = (Button) layout_shareCenter.findViewById(R.id.btn_shareSina);
		btnQQ = (Button) layout_shareCenter.findViewById(R.id.btn_shareQQ);
		btnRenRen = (Button) layout_shareCenter.findViewById(R.id.btn_shareRenRen);
		btnKaixin = (Button) layout_shareCenter.findViewById(R.id.btn_shareKaiXin);
		
		
		//点击注销页面，退出当前activity，弹出登录窗口
//		findViewById(R.id.logout).setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				//注销用户，首先清楚内容提供者中的参数
//				Uri uri = LoginInfoProvider.LoginInfo.CONTENT_URI;
//				ContentValues values=new ContentValues();
//				values.put("userid", 0);
//				values.put("token", "");
//				getContentResolver().insert(uri, values);
//				//清空sp中的参数
//				LoginUtil.setUserId(context, 0);
//				LoginUtil.setToken(context, "");
//				
//				//更新WidgetService
//				context.startService(new Intent(context,WidgetService.class));
//				//调用netService发送退出报文
//				Intent netService=new Intent(context,NetService.class);
//				netService.putExtra(Global.INTENT_EXTRA_LOGIN_STATE,Global.LOGOUT);
//				context.startService(netService);
//				//更改按钮显示状态
//				((MainActivity)getParent()).refreshBtnState();
//				//清空QQ绑定的oauth
//				QQWebViewActivity.TokenStore.clear(context);
//				startActivity(new Intent(context, LoginActivity.class));
//				finish();
//			}
//		});
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (userCenterInfo!=null) {
			outState.putParcelable("userCenterInfo", userCenterInfo);
		}
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Bundle parcelable = savedInstanceState.getParcelable("userCenterInfo");
		if (parcelable!=null) {
			userCenterInfo=parcelable;
		}
	}
	/**
	 * 切换为展示状态
	 * 
	 * @param view
	 */
	public void changeToDisplayState(View view) {
		editDialog.show();
		saveEditInfoToBundle();
		new Thread(new Runnable() {
			public void run() {
				try {
					InfoUtil.editUserCenterInfo(context, JsonUtil.parseUserCenterInfo2Json(context, userCenterInfo));
					handler.sendEmptyMessage(EDIT_USER_CENTER_SUCCESS);
				} catch (Exception e) {
					Log.e("test", e.getMessage(),e);
					DeBugUtil.printException(context, e);
					handler.sendEmptyMessage(EDIT_USER_CENTER_ERROR);
				}
			}
		}).start();
	}
	
	/**
	 * 切换为编辑状态
	 * 	在此之前，对Bundle进行克隆，用于编辑保存失败时的回显
	 * @param view
	 */
	public void changeToEditState(View view) {
		cloneBundle = new Bundle(userCenterInfo);
		setEditContent();
		displayState.setVisibility(View.GONE);
		editState.setVisibility(View.VISIBLE);
	}

	//点击进入设置SNS绑定页面
	public void setShareConfig(View view) {
		setContentView(layout_shareCenter,layoutParams);
	}
	//返回用户中心界面
	public void backToUserCenter(View view) {
		setContentView(layout_userCenter,layoutParams);
	}
	
	
	//分享新浪微博
	public void shareToSina(View view) {
		Weibo weibo=Weibo.getInstance();
		weibo.setupConsumerConfig(SinaWeiBoHelper.CONSUMER_KEY, SinaWeiBoHelper.CONSUMER_SECRET);
		weibo.setRedirectUrl("http://www.net-east.com/");
		weibo.authorize(this, new SinaWeiBoHelper.AuthDialogListener(context,btnSina));
	}
	
	//分享腾讯微博
	public void shareToQQ(View view) {
		Intent intent=new Intent(context,QQWebViewActivity.class);
		startActivityForResult(intent, 1);
	}
	//分享开心网
	public void shareToKaiXin(View view) {
		Kaixin kaixin=Kaixin.getInstance();
		if (kaixin.isSessionValid()) {
			return;
		}
		//没有绑定，点击进行绑定
		String[] permissions = { "basic", "create_records" };
		kaixin.authorize(context, permissions,
				new KaixinHelper.KaixinRequestAuthListener(context, btnKaixin));
	}
	
	
	//分享人人网
	public void shareToRenRen(View view) {
		renren=new Renren(RENREN_API_KEY, RENREN_Secret_Key, RENREN_APP_ID, context);
		renren.authorize(context, new RenrenAuthListener(){
			public void onComplete(Bundle values) {
				btnRenRen.setText("已绑定");
				btnRenRen.setEnabled(false);
				Toast.makeText(context, "绑定人人网成功", Toast.LENGTH_SHORT).show();
			}
			public void onRenrenAuthError(RenrenAuthError renrenAuthError) {
				Log.i("test", renrenAuthError.getErrorDescription());
			}
			public void onCancelLogin() {
				Log.i("test", "onCancelLogin");
			}
			public void onCancelAuth(Bundle values) {
				Log.i("test", "onCancelAuth");
			}});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//返回是绑定QQ的结果
		if (resultCode==RESULT_OK&&requestCode==1) {
			Uri uri = data.getData();
			String oauth_token = uri.getQueryParameter("oauth_token");
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");
			Log.i("test", "oauth_token=" + oauth_token);
			Log.i("test", "oauth_verifier=" + oauth_verifier);
			QQWebViewActivity.oAuth.setOauth_token(oauth_token);
			QQWebViewActivity.oAuth.setOauth_verifier(oauth_verifier);
			new Thread(new Runnable() {
					public void run() {
						try {
							OAuthClient auth=QQWebViewActivity.auth;
							OAuth oAuth=QQWebViewActivity.oAuth;
							oAuth=auth.accessToken(oAuth);
							Log.i("test", "Oauth_token="+oAuth.getOauth_token());
							Log.i("test", "Oauth_token_secret="+oAuth.getOauth_token_secret());
							QQWebViewActivity.TokenStore.store(context, oAuth);
							handler.sendEmptyMessage(BANDING_QQ_SUCCESS);
						} catch (Exception e) {
							Log.e("test", e.getMessage(),e);
							handler.sendEmptyMessage(BANDING_QQ_ERROR);
						}
					}
			}).start();
		}
	}
}
